package com.zhangxiaofanfan.hotcode.fourth.third;


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked">两数之和</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-20 22:55:05
 */
public class HotCode001 {
    public static void main(String[] args) {

    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                if ((target >> 1) == nums[i]) {
                    return new int[] {map.get(nums[i]), i};
                }
            } else {
                map.put(nums[i], i);
            }
        }
        Arrays.sort(nums);
        int left = 0, right = nums.length - 1, sum;
        while (left < right) {
            sum = nums[left] + nums[right];
            if (sum == target) {
                return new int[] {map.get(nums[left]), map.get(nums[right])};
            } else if (sum > target) {
                right--;
            } else {
                left++;
            }
        }
        return null;
    }
}
